package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.encrypt.symmetric.AES;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyDingDongJinRong;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeDingDongJinRong;
import com.ts.api.module.api.convert.core.annotation.ApiPlan;
import com.ts.api.module.api.convert.core.annotation.ApiPlanConvertType;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 安心分期（出）叮咚金融半流程28分
 * 链接：https://fxe0ir2d04q.feishu.cn/docx/Fx0Bdqps3oIVedx0xhwcU3xknuc?from=from_copylink 
 *
 * @author gwc
 * @create 2025-08-07 下午12:17
 */
@ApiPlan(productId = "398", type = ApiPlanConvertType.PLAT_PHONE_MD5)
public class ApiPlatDingDongJinRongPhoneMd5ConvertV2 implements ApiPlatformPhoneMd5ConvertHandler {

    private static final String KEY = "M69VYC5rlArWAFXP";
    private static final String ORG_ID = "202306554";

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) throws Exception {
        // 创建对应撞库实体类
        ApiPlatDataExchangeDingDongJinRong dingDongJinRongData = new ApiPlatDataExchangeDingDongJinRong();
        // 拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiDataExchangeParameter);
        // 手机号md5加密（小写）
        dingDongJinRongData.setPhoneMd5(apiDataExchangeParameter.getPhoneMd5());
        // 城市名称（例如常州市）
        dingDongJinRongData.setCity(apiDataExchangeParameter.getCity());
        // 城市编码(例如 北京市 110100)
        dingDongJinRongData.setCityCode(apiDataExchangeParameter.getAreaCode());
        // 年龄
        dingDongJinRongData.setAge(apiFieldConverter.getAgeInt());
        // 性别 1：男，2：女，0：未知
        Integer sex = ChooseEq.create()
                .when(apiDataExchangeParameter.getSex(), "0", 1)
                .when(apiDataExchangeParameter.getSex(), "1", 2)
                .when(apiDataExchangeParameter.getSex(), "2", 0)
                .end(1);
        dingDongJinRongData.setGender(sex);
        // 贷款时间 2：6个月，3：12个月，4：24个月，5：36个月
        Integer loanTerm = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanTerm(), "1", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "2", 2)
                .when(apiDataExchangeParameter.getLoanTerm(), "3", 3)
                .when(apiDataExchangeParameter.getLoanTerm(), "4", 4)
                .when(apiDataExchangeParameter.getLoanTerm(), "5", 5)
                .when(apiDataExchangeParameter.getLoanTerm(), "6", 5)
                .end(2);
        dingDongJinRongData.setLoanTime(loanTerm);
        // 职业 1：上班族，2：自由职业，3：私营企业主，4：公务员/国企
        Integer career = ChooseEq.create()
                .when(apiDataExchangeParameter.getCareer(), "1", 1)
                .when(apiDataExchangeParameter.getCareer(), "2", 2)
                .when(apiDataExchangeParameter.getCareer(), "3", 3)
                .when(apiDataExchangeParameter.getCareer(), "4", 4)
                .when(apiDataExchangeParameter.getCareer(), "5", 3)
                .end(1);
        dingDongJinRongData.setProfession(career);
        // 芝麻分 1：600-650，2：650-700，3：700以上，4：无，5：600以下
        Integer zhima = ChooseEq.create()
                .when(apiDataExchangeParameter.getSesameCredit(), "1", 5)
                .when(apiDataExchangeParameter.getSesameCredit(), "2", 1)
                .when(apiDataExchangeParameter.getSesameCredit(), "3", 2)
                .when(apiDataExchangeParameter.getSesameCredit(), "4", 3)
                .end(4);
        dingDongJinRongData.setZhima(zhima);
        // 公积金 1：6个月以下，2：6-12个月，3：12个月以上，4：无
        Integer providentFund = ChooseEq.create()
                .when(apiDataExchangeParameter.getProvidentFund(), "1", 4)
                .when(apiDataExchangeParameter.getProvidentFund(), "2", 1)
                .when(apiDataExchangeParameter.getProvidentFund(), "3", 2)
                .when(apiDataExchangeParameter.getProvidentFund(), "4", 1)
                .end(4);
        dingDongJinRongData.setProvidentFund(providentFund);
        // 社保 1：6个月以下，2：6-12个月，3：12个月以上，4：无
        Integer socialSecurity = ChooseEq.create()
                .when(apiDataExchangeParameter.getSocialSecurity(), "1", 4)
                .when(apiDataExchangeParameter.getSocialSecurity(), "2", 1)
                .when(apiDataExchangeParameter.getSocialSecurity(), "3", 2)
                .when(apiDataExchangeParameter.getSocialSecurity(), "4", 1)
                .end(4);
        dingDongJinRongData.setSocialSecurity(socialSecurity);
        // 名下房产 1：有房产，2：无房产
        Integer house = ChooseEq.create()
                .when(apiDataExchangeParameter.getRealEstateInfo(), "1", 2)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "2", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "3", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "4", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "5", 1)
                .when(apiDataExchangeParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        dingDongJinRongData.setHouse(house);
        // 逾期记录 1：信用良好，2：当前逾期中
        Integer overdue = ChooseEq.create()
                .when(apiDataExchangeParameter.getOverdue(), "1", 1)
                .when(apiDataExchangeParameter.getOverdue(), "2", 2)
                .when(apiDataExchangeParameter.getOverdue(), "3", 1)
                .end(2);
        dingDongJinRongData.setOverdue(overdue);
        // 保单 0：6个月以下，1：6-12个月，2：12个月以上，3：无
        Integer baodanIs = ChooseEq.create()
                .when(apiDataExchangeParameter.getInsurancePolicy(), "1", 3)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "2", 1)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "3", 2)
                .when(apiDataExchangeParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        dingDongJinRongData.setCommericalInsurance(baodanIs);
        // 名下车产 1：有车产，2：无车产
        Integer vehicle = ChooseEq.create()
                .when(apiDataExchangeParameter.getCarInfo(), "1", 2)
                .when(apiDataExchangeParameter.getCarInfo(), "2", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "3", 1)
                .when(apiDataExchangeParameter.getCarInfo(), "4", 1)
                .end(2);
        dingDongJinRongData.setVehicle(vehicle);
        // 贷款额度 1：30000，2：50000，3：100000，4：200000
        Integer money = ChooseEq.create()
                .when(apiDataExchangeParameter.getLoanAmount(), "1", 1)
                .when(apiDataExchangeParameter.getLoanAmount(), "2", 2)
                .when(apiDataExchangeParameter.getLoanAmount(), "3", 3)
                .when(apiDataExchangeParameter.getLoanAmount(), "4", 4)
                .end(1);
        dingDongJinRongData.setLoanAmount(money);
        // appKey
        dingDongJinRongData.setAppKey(KEY);
        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(dingDongJinRongData));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", ORG_ID);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if(!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        JSONObject resData = jsonObject.getJSONObject("data");
        if (ValidParam.isEmpty(resData)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        //  分润前价格
        BigDecimal price = resData.getBigDecimal("price");
        //  订单号
        String orderId = resData.getString("orderId");
        //  授权地址
        String url = resData.getString("redirectUrl");

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setApplyId(orderId);
        result.setCallUrl(url);
        result.setProductName("叮咚金融");
        result.setDisplayName("叮咚金融");
        return result;
    }

    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) throws Exception {
        // 创建对应撞库实体类
        ApiPlatApplyDingDongJinRong dingDongJinRongData = new ApiPlatApplyDingDongJinRong();
        // 拓展
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        // 姓名，例如张三
        dingDongJinRongData.setName(apiApplyParameter.getUserName());
        // 手机号
        dingDongJinRongData.setPhone(apiApplyParameter.getPhone());
        // ip
        if (ValidParam.isNotEmpty(apiApplyParameter.getIp())) {
            dingDongJinRongData.setIp(apiApplyParameter.getIp());
        } else {
            dingDongJinRongData.setIp("127.0.0.1");
        }
        // 城市名称（例如常州市）
        dingDongJinRongData.setCity(apiApplyParameter.getCity());
        // 城市编码(例如 北京市 110100)
        dingDongJinRongData.setCityCode(apiApplyParameter.getAreaCode());
        // 年龄
        dingDongJinRongData.setAge(apiFieldConverter.getAgeInt());
        // 性别 1：男，2：女，0：未知
        Integer sex = ChooseEq.create()
                .when(apiApplyParameter.getSex(), "0", 1)
                .when(apiApplyParameter.getSex(), "1", 2)
                .when(apiApplyParameter.getSex(), "2", 0)
                .end(1);
        dingDongJinRongData.setGender(sex);
        // 贷款时间 2：6个月，3：12个月，4：24个月，5：36个月
        Integer loanTerm = ChooseEq.create()
                .when(apiApplyParameter.getLoanTerm(), "1", 2)
                .when(apiApplyParameter.getLoanTerm(), "2", 2)
                .when(apiApplyParameter.getLoanTerm(), "3", 3)
                .when(apiApplyParameter.getLoanTerm(), "4", 4)
                .when(apiApplyParameter.getLoanTerm(), "5", 5)
                .when(apiApplyParameter.getLoanTerm(), "6", 5)
                .end(2);
        dingDongJinRongData.setLoanTime(loanTerm);
        // 职业 1：上班族，2：自由职业，3：私营企业主，4：公务员/国企
        Integer career = ChooseEq.create()
                .when(apiApplyParameter.getCareer(), "1", 1)
                .when(apiApplyParameter.getCareer(), "2", 2)
                .when(apiApplyParameter.getCareer(), "3", 3)
                .when(apiApplyParameter.getCareer(), "4", 4)
                .when(apiApplyParameter.getCareer(), "5", 3)
                .end(1);
        dingDongJinRongData.setProfession(career);
        // 芝麻分 1：600-650，2：650-700，3：700以上，4：无，5：600以下
        Integer zhima = ChooseEq.create()
                .when(apiApplyParameter.getSesameCredit(), "1", 5)
                .when(apiApplyParameter.getSesameCredit(), "2", 1)
                .when(apiApplyParameter.getSesameCredit(), "3", 2)
                .when(apiApplyParameter.getSesameCredit(), "4", 3)
                .end(4);
        dingDongJinRongData.setZhima(zhima);
        // 公积金 1：6个月以下，2：6-12个月，3：12个月以上，4：无
        Integer providentFund = ChooseEq.create()
                .when(apiApplyParameter.getProvidentFund(), "1", 4)
                .when(apiApplyParameter.getProvidentFund(), "2", 1)
                .when(apiApplyParameter.getProvidentFund(), "3", 2)
                .when(apiApplyParameter.getProvidentFund(), "4", 1)
                .end(4);
        dingDongJinRongData.setProvidentFund(providentFund);
        // 社保 1：6个月以下，2：6-12个月，3：12个月以上，4：无
        Integer socialSecurity = ChooseEq.create()
                .when(apiApplyParameter.getSocialSecurity(), "1", 4)
                .when(apiApplyParameter.getSocialSecurity(), "2", 1)
                .when(apiApplyParameter.getSocialSecurity(), "3", 2)
                .when(apiApplyParameter.getSocialSecurity(), "4", 1)
                .end(4);
        dingDongJinRongData.setSocialSecurity(socialSecurity);
        // 名下房产 1：有房产，2：无房产
        Integer house = ChooseEq.create()
                .when(apiApplyParameter.getRealEstateInfo(), "1", 2)
                .when(apiApplyParameter.getRealEstateInfo(), "2", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "3", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "4", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "5", 1)
                .when(apiApplyParameter.getRealEstateInfo(), "6", 1)
                .end(2);
        dingDongJinRongData.setHouse(house);
        // 逾期记录 1：信用良好，2：当前逾期中
        Integer overdue = ChooseEq.create()
                .when(apiApplyParameter.getOverdue(), "1", 1)
                .when(apiApplyParameter.getOverdue(), "2", 2)
                .when(apiApplyParameter.getOverdue(), "3", 1)
                .end(2);
        dingDongJinRongData.setOverdue(overdue);
        // 保单 0：6个月以下，1：6-12个月，2：12个月以上，3：无
        Integer baodanIs = ChooseEq.create()
                .when(apiApplyParameter.getInsurancePolicy(), "1", 3)
                .when(apiApplyParameter.getInsurancePolicy(), "2", 1)
                .when(apiApplyParameter.getInsurancePolicy(), "3", 2)
                .when(apiApplyParameter.getInsurancePolicy(), "4", 0)
                .end(3);
        dingDongJinRongData.setCommericalInsurance(baodanIs);
        // 名下车产 1：有车产，2：无车产
        Integer vehicle = ChooseEq.create()
                .when(apiApplyParameter.getCarInfo(), "1", 2)
                .when(apiApplyParameter.getCarInfo(), "2", 1)
                .when(apiApplyParameter.getCarInfo(), "3", 1)
                .when(apiApplyParameter.getCarInfo(), "4", 1)
                .end(2);
        dingDongJinRongData.setVehicle(vehicle);
        // 贷款额度 1：30000，2：50000，3：100000，4：200000
        Integer money = ChooseEq.create()
                .when(apiApplyParameter.getLoanAmount(), "1", 1)
                .when(apiApplyParameter.getLoanAmount(), "2", 2)
                .when(apiApplyParameter.getLoanAmount(), "3", 3)
                .when(apiApplyParameter.getLoanAmount(), "4", 4)
                .end(1);
        dingDongJinRongData.setLoanAmount(money);
        // appKey
        dingDongJinRongData.setAppKey(KEY);
        // 撞库时返回的订单号
        dingDongJinRongData.setOrderId(apiApplyParameter.dataExchangeApplyId());
        // 用户授权协议
        dingDongJinRongData.setAgreeProtocol(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));

        // 加密
        AES aes = AES.createEcb(KEY.getBytes());
        String data = aes.encryptToBase64Str(JsonUtils.toJson(dingDongJinRongData));

        Map<String, Object> map = MapUtils.newHashMap(newMap -> {
            newMap.put("orgId", ORG_ID);
            newMap.put("data", data);
        });
        return JsonUtils.toJson(map);
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) throws Exception {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        JSONObject jsonObject = JsonUtils.get(requestVO.getBody());
        String orgId = jsonObject.getString("orderId");

        RespPlatformNoticeApply applyNotice = new RespPlatformNoticeApply();
        applyNotice.setApplyId(orgId);

        return applyNotice;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        boolean b = apiBizStatus.hasBizSuc();

        if (b) {
            return MapUtils.newHashMap(newHashMap -> {
                newHashMap.put("code", 0);
                newHashMap.put("msg", "操作成功");
            });
        }
        return MapUtils.newHashMap(newHashMap -> {
            newHashMap.put("code", 500);
            newHashMap.put("msg", "操作失败");
        });
    }
}
